<?php

class MenuItemController extends SBaseController
{
    /**
     * @var string the default layout for the views. Defaults to 'column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout='main';

    /**
     * @var CActiveRecord the currently loaded data model instance.
     */
    private $_model;

    /**
     * Displays a particular model.
     */
    public function actionView()
    {
        $this->layout="detail";
        $this->render('view',array(
            'model'=>$this->loadModel(),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        //print_r($menu);
        $model = new MenuItem();
		$criteria=new CDbCriteria;
		$model->sorder = Common::getNewestPosition($model);
		$menu = $this->loadMenu();
        $model->menu_id = Lvc::getCache('menu_parent_id_cache'.$menu->id);
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_POST['MenuItem']))
        {
            $model->attributes=$_POST['MenuItem'];

            $p = new CHtmlPurifier();
            foreach($model->attributes as $key=>$val)
            {
                $model->$key = $p->purify($val);
            }
            if($model->save())
            {
                $model->deleteCache();
                MenuItem::model()->rebuildSOrder();
                Yii::app()->user->setFlash('message', Yii::t('BackEnd', 'Create successfully.'));
                $this->redirect(array('create','mId'=>$model->menu_id));
            }else{
                echo '<pre>';print_r($model->getErrors());echo '</pre>';
            }
        }

        $this->layout="detail";
        $this->render('create',array(
            'model'=>$model,
            'menu' => $menu
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     */
    public function actionUpdate()
    {
        $model=$this->loadModel();
        $oldSortOrder = $model->sorder;
        $p = new CHtmlPurifier;
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        if(isset($_POST['MenuItem']))
        {
            $model->attributes=$_POST['MenuItem'];
            foreach($model->attributes as $key=>$val)
            {
                if ( ! in_array($key, array('id', 'sorder')))
                {
                        $model->$key = $p->purify($val);
                }
            }
            if($model->save())
            {
                //Delete old cache
                $model->deleteCache();
                
                if($oldSortOrder!=$_POST['MenuItem']['sorder']) MenuItem::model()->rebuildSOrder();
                Yii::app()->user->setFlash('message', Yii::t('BackEnd', 'Update successfully.'));
                $this->redirect(array('view','id'=>$model->id));
            }
        }
        $this->layout="detail";
        $this->render('update',array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     */
    public function actionDelete()
    {
        if(Yii::app()->request->isPostRequest)
        {
            // we only allow deletion via POST request
            $model = $this->loadModel();
            
            //Delete old cache
            $model->deleteCache();
                
            $menuId = $model->menu_id;
            $model->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser            
            if(!isset($_GET['ajax']))
            {
                MenuItem::model()->rebuildSOrder();
                $this->redirect(array('index', 'mId'=>$menuId));
            }
        }
        else
            throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
    }

    public function actionDeleteAll(){
        if(isset($_POST['select-row'])&&is_array($_POST['select-row']))
        {
            $ids = $_POST['select-row'];
            $menu = $this->loadMenu();
            if($ids)
            {
                $ids = implode(',', $ids);
                /* delete cache menu by id menu */
                $filters = array();
                $filters['inId'] = $ids;
                $menus = MenuItem::model()->search($filters);
                if($menus)
                {
                    $model = new MenuItem();
                    foreach ( $menus as $item ){
                        //Delete old cache
                        $model->deleteCache();
                    }
                }
                MenuItem::model()->deleteAll("id in ($ids)");
            }
            MenuItem::model()->rebuildSOrder($menu->id);
            $this->redirect(array('admin', 'mId'=>$menu->id));
        }else{
            throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
        }
    }
    
    /**
     * Manages all models.
     */
    public function actionAdmin()
    {
        $menu = $this->loadMenu();
        if(!isset($_GET['ajax']) && isset($_POST['sorder']))
        {
            $ids = $_POST['ids'];
            $sorder = $_POST['sorder'];
            for($i=0; $i<count($ids); $i++){
                $model = MenuItem::model()->findByPk($ids[$i]);
                $model->sorder = $sorder[$i];
                $model->save();
            }
            MenuItem::model()->rebuildSOrder();
            Yii::app()->user->setFlash('message', Yii::t('BackEnd', 'Rebuild all sort order successfully.'));
        }

        $model = new MenuItem('search');
        $model->parent_id = '';
        $model->sorder = '';
        $model->status = '';
        $model->menu_id = $menu->id;

        if(isset($_GET['MenuItem']))
            $model->attributes=$_GET['MenuItem'];

        $this->layout="list";
        $this->render('admin',array(
            'model'=>$model,
            'menu' => $menu,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     */
    public function loadModel()
    {
        if($this->_model===null)
        {
            if(isset($_GET['id']))
                $this->_model=MenuItem::model()->findbyPk($_GET['id']);
            if($this->_model===null)
                throw new CHttpException(404,'The requested page does not exist.');
        }
        return $this->_model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if(isset($_POST['ajax']) && $_POST['ajax']==='menu-item-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actionChangeStatus(){
        if($_POST['ajax']&&$_POST['id']){
            $model = MenuItem::model()->findByPk($_POST['id']);
            if($model->status == MenuItem::STATUS_ENABLED) $model->status = MenuItem::STATUS_DISABLED;
            elseif($model->status == MenuItem::STATUS_DISABLED) $model->status = MenuItem::STATUS_ENABLED;
            
             $model->deleteCache();
             
            $model->save();
            Yii::app()->end();
        }else
            throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
    }

    public function loadMenu($redirect = true)
    {
        if($this->_model===null)
        {
            $id = Lvc::getCache('menu_parent_id_cache'.(int) $_GET['mId']);
            if(!$id){
                $id = (int) $_GET['mId'];
                $this->_model=Menu::model()->findbyPk($id);
            }
//            if($redirect && $this->_model===null)
//                $this->redirect(Yii::app()->request->baseUrl.'/menu/admin.html');
        }
        return $this->_model;
    }
	
	public function actionGetSorder()
	{
		if ( ! $_POST['rootItem'])
			$item = 0;
		else
			$item = $_POST['rootItem'];
		$criteria=new CDbCriteria;
		$criteria->select='sorder';  // only select the 'title' column
		$criteria->condition='parent_id=:postID order by sorder desc';
		$criteria->params=array(':postID'=> $item);
		$model=MenuItem::model()->find($criteria)->sorder;
		$model+=1;
		echo $model;
		return;
	}
}